package com.atguigu.bigdata.spark.core.rdd.operator.transform;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

public class Spark17_RDD_Operator_Transform2_JAVA {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("sparkCore");
        JavaSparkContext sc = new JavaSparkContext(conf);

        List<Tuple2<String, Integer>> list = Arrays.asList(new Tuple2<String,Integer>("a", 1),
                new Tuple2<String,Integer>("a",2), new Tuple2<String, Integer>("a", 3),
                new Tuple2<String, Integer>("a", 4));
        JavaPairRDD<String, Integer> rdd = sc.<String, Integer> parallelizePairs(list,2);

        //rdd.aggregateByKey(0)(_+_, _+_).collect.foreach(println)

        // 如果聚合计算时，分区内和分区间计算规则相同，spark提供了简化的方法  分区内外算子逻辑一样
        JavaPairRDD<String, Integer> foldBykey = rdd.foldByKey(0, new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer integer, Integer integer2) throws Exception {
                return Math.max(integer,integer2);
            }
        });

        System.out.println(foldBykey.collect().toString());

        sc.stop();
    }
}
